<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;

class BeforeConvertRequestToSnakeCase
{
    public function handle(Request $request, \Closure $next)
    {
        $data = $this->convert($request->all());
        $request->merge($data);
        if(is_object($request->route()->controller) && method_exists($request->route()->controller,'getServices'))
        {
            $request->route()->controller->getServices()->setData($data);
        }
        return $next($request);
    }

    protected function convert($data) {
        if (!is_array($data)) return $data;

        $result= [];

        foreach ($data as $k=> $value) {
            if(!empty($val) && is_string($val)){
                $val = trim($val);
            }
            $value = is_string($value) ?  trim($value) : $value;
            $result[\Str::snake($k)] = is_array($value) ? $this->convert($value) : $value;
        }


        return $result;
    }
}
